from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):
    # 审核状态选项
    DRAFT = 'draft'
    PENDING = 'pending'
    FIRST_APPROVED = 'first_approved'
    APPROVED = 'approved'
    REJECTED = 'rejected'
    PUBLISHED = 'published'
    WITHDRAWN = 'withdrawn'
    
    STATUS_CHOICES = [
        (DRAFT, '草稿'),
        (PENDING, '待审核'),
        (FIRST_APPROVED, '一审通过'),
        (APPROVED, '审核通过'),
        (REJECTED, '审核拒绝'),
        (PUBLISHED, '已发布'),
        (WITHDRAWN, '已撤回'),
    ]
    
    title = models.CharField(max_length=200, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    categories = models.ManyToManyField('Category', through='ArticleCategory', verbose_name='分类')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    published = models.BooleanField(default=False, verbose_name='是否发布')
    
    # 添加审核状态相关字段
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=DRAFT, verbose_name='审核状态')
    submitted_at = models.DateTimeField(null=True, blank=True, verbose_name='提交审核时间')
    first_reviewed_at = models.DateTimeField(null=True, blank=True, verbose_name='初审时间')
    final_reviewed_at = models.DateTimeField(null=True, blank=True, verbose_name='终审时间')
    published_at = models.DateTimeField(null=True, blank=True, verbose_name='发布时间')
    withdrawn_at = models.DateTimeField(null=True, blank=True, verbose_name='撤回时间')
    
    class Meta:
        verbose_name = '文章'
        verbose_name_plural = '文章'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title


class Category(models.Model):
    name = models.CharField(max_length=100, verbose_name='分类名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='分类编码')
    description = models.TextField(blank=True, verbose_name='分类描述')
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, verbose_name='上级分类')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '分类'
        verbose_name_plural = '分类'
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        # 如果没有设置code，则自动生成
        if not self.code:
            # 生成唯一的code
            base_code = self.name.replace(' ', '_').lower()
            code = base_code
            counter = 1
            while Category.objects.filter(code=code).exists():
                code = f"{base_code}_{counter}"
                counter += 1
            self.code = code
        super().save(*args, **kwargs)
    
    def get_children(self):
        # 获取直接子分类
        return Category.objects.filter(parent=self)
    
    def get_all_children(self):
        # 获取所有子分类（递归）
        children = []
        for child in self.get_children():
            children.append(child)
            children.extend(child.get_all_children())
        return children
    
    def get_full_path(self):
        # 获取完整分类路径
        path = [self.name]
        parent = self.parent
        while parent:
            path.append(parent.name)
            parent = parent.parent
        return ' > '.join(reversed(path))
    
    def is_root(self):
        # 判断是否为根分类
        return self.parent is None

class ArticleCategory(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    
    class Meta:
        unique_together = ('article', 'category')
        verbose_name = '文章分类'
        verbose_name_plural = '文章分类'
    
    def __str__(self):
        return f"{self.article.title} - {self.category.name}"

# 部门模型
class Department(models.Model):
    name = models.CharField(max_length=100, verbose_name='部门名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='部门编码')
    description = models.TextField(blank=True, verbose_name='描述')
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, verbose_name='上级部门')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_active = models.BooleanField(default=True, verbose_name='状态')
    
    class Meta:
        verbose_name = '部门'
        verbose_name_plural = '部门'
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    def get_children(self):
        # 获取直接子部门
        return Department.objects.filter(parent=self)
    
    def get_all_children(self):
        # 获取所有子部门（递归）
        children = []
        for child in self.get_children():
            children.append(child)
            children.extend(child.get_all_children())
        return children

# 权限组模型
class PermissionGroup(models.Model):
    name = models.CharField(max_length=100, verbose_name='权限组名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='权限组编码')
    description = models.TextField(blank=True, verbose_name='描述')
    permissions = models.ManyToManyField('Permission', blank=True, verbose_name='权限列表')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_active = models.BooleanField(default=True, verbose_name='状态')
    
    class Meta:
        verbose_name = '权限组'
        verbose_name_plural = '权限组'
        ordering = ['name']
    
    def __str__(self):
        return self.name

# 权限模型
class Permission(models.Model):
    name = models.CharField(max_length=100, verbose_name='权限名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='权限编码')
    description = models.TextField(blank=True, verbose_name='描述')
    module = models.CharField(max_length=50, verbose_name='模块')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '权限'
        verbose_name_plural = '权限'
        ordering = ['module', 'name']
    
    def __str__(self):
        return f"{self.module} - {self.name}"

# 用户组模型
class UserGroup(models.Model):
    name = models.CharField(max_length=100, verbose_name='用户组名称')
    code = models.CharField(max_length=50, unique=True, verbose_name='用户组编码')
    description = models.TextField(blank=True, verbose_name='描述')
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='所属部门')
    permission_groups = models.ManyToManyField(PermissionGroup, blank=True, verbose_name='权限组')
    users = models.ManyToManyField(User, through='UserGroupMembership', verbose_name='用户')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_active = models.BooleanField(default=True, verbose_name='状态')
    
    class Meta:
        verbose_name = '用户组'
        verbose_name_plural = '用户组'
        ordering = ['name']
    
    def __str__(self):
        return self.name

# 用户组成员关系模型
class UserGroupMembership(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    user_group = models.ForeignKey(UserGroup, on_delete=models.CASCADE)
    role = models.CharField(max_length=50, blank=True, verbose_name='组内角色')  # 如组长等
    joined_at = models.DateTimeField(auto_now_add=True, verbose_name='加入时间')
    
    class Meta:
        unique_together = ('user', 'user_group')
        verbose_name = '用户组成员'
        verbose_name_plural = '用户组成员'
    
    def __str__(self):
        return f"{self.user.username} - {self.user_group.name}"

# 审核记录模型
class ArticleReview(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name='文章')
    reviewer = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='审核人')
    action = models.CharField(max_length=20, verbose_name='审核操作')  # 通过/拒绝
    status_before = models.CharField(max_length=20, verbose_name='审核前状态')
    status_after = models.CharField(max_length=20, verbose_name='审核后状态')
    comment = models.TextField(blank=True, verbose_name='审核备注')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='审核时间')
    
    class Meta:
        verbose_name = '文章审核记录'
        verbose_name_plural = '文章审核记录'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.article.title} - {self.reviewer.username} - {self.action}"

# 栏目审核流程配置模型
class CategoryReviewProcess(models.Model):
    REVIEW_LEVEL_CHOICES = [
        (1, '一级审核'),
        (2, '二级审核'),
    ]
    
    category = models.OneToOneField(Category, on_delete=models.CASCADE, verbose_name='栏目')
    review_level = models.IntegerField(choices=REVIEW_LEVEL_CHOICES, default=2, verbose_name='审核级别')
    first_reviewer_group = models.ForeignKey(
        UserGroup, 
        on_delete=models.SET_NULL, 
        blank=True, 
        null=True, 
        related_name='first_review_processes',
        verbose_name='初审员用户组'
    )
    final_reviewer_group = models.ForeignKey(
        UserGroup, 
        on_delete=models.SET_NULL, 
        blank=True, 
        null=True, 
        related_name='final_review_processes',
        verbose_name='终审员用户组'
    )
    auto_publish = models.BooleanField(default=False, verbose_name='是否自动发布')
    notify_author = models.BooleanField(default=True, verbose_name='是否通知作者')
    notify_reviewer = models.BooleanField(default=True, verbose_name='是否通知审核员')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '栏目审核流程'
        verbose_name_plural = '栏目审核流程'
    
    def __str__(self):
        return f"{self.category.name} - 审核流程"
